<template>
	<div>
		<div style="padding-top: 2vw">
			<div class="tag-group" v-if="is_ctdd_show">
				<div class="tag-label">分析粒度</div>
				<div class="tag-cell">
					<div class="tag-item" v-for="(item, index) in granularityList" :key="index"
						:class="{ active: tagesForm.type === index + 1 }" @click="granularityClick(index + 1)">
						{{ item.label }}
					</div>
				</div>
			</div>
			<!-- 片区类型 -->
			<div class="tag-group">
				<div class="tag-label">片区类型</div>
				<div class="today">
					<el-select size="small" v-model="areaTypeCode" @change="areaTypeCodeChange" placeholder="请选择">
						<el-option v-for="item in areaTypeCodeList" :key="item.value" :label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</div>
			</div>
			<!-- 实时粒度 -->
			<div class="tag-group">
				<div class="tag-label">分析日期</div>
				<div class="today">
					<div class="date-box">{{ today }}</div>
					<div class="refresh" @click="realRefresh">5分钟自动刷新</div>
				</div>
			</div>
			<!-- 交通定期分析 -->
			<div class="tag-group" v-if="is_ctdd_show">
				<div class="tag-label">道路标签</div>
				<div class="tag-cell">
					<template v-for="(item, index) in roadTagList" :key="index">
						<div class="tag-item" v-if="item.value > 1"
							:class="{ active: tagesForm.roadType === index + 1 }"
							@click="tagClick(index + 1, 'roadType')">
							{{ item.label }}
						</div>
					</template>
				</div>
			</div>
			<!-- 交通定期分析 -->
			<!-- <div class="tag-group">
        <div class="tag-label">分析时段</div>
        <div class="date">
          <div>
             <el-time-picker
                v-model="periodRange"
                is-range
                range-separator="至"
                start-placeholder="开始时段"
                end-placeholder="结束时段"
              />
            <el-select v-model="sameDay.period" placeholder="请选择">
              <el-option
                v-for="(item, index) in periodOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div> -->
			<!-- 自定义日期 -->
			<div v-if="tagesForm.type == 5">
				<div class="tag-group">
					<div class="tag-label">自定义日期选择</div>
					<div class="date">
						<el-date-picker v-model="analysisDate" type="daterange" range-separator="至"
							value-format="YYYY-MM-DD" format="YYYY-MM-DD" start-placeholder="选择开始日期"
							end-placeholder="选择结束日期" @change="changeAnalysisDate" />
					</div>
				</div>
				<!-- <div class="tag-group">
          <div class="tag-label">分析时段</div>
          <div class="date">
            <el-select
              style="width: 100%;"
              v-model="sameDay.period"
              placeholder="请选择"
              @change="changeTable"
            >
              <el-option
                v-for="(item, index) in periodOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div> -->
			</div>
			<!-- 搜索 -->
			<div class="search">
				<div class="search-input"><el-input v-model="queryForm.areaName" placeholder="请输入" :prefix-icon="Search"
						@keyup.enter.native="getList" @change="getList" clearable /></div>
				<!-- <div class="export">
          <span>导出Excel</span>
        </div> -->
			</div>

			<!-- 表格 -->
			<!-- <table-views /> -->
			<!-- <div
        class="table"
        v-loading="tableLoading"
        v-if="tableData && tableData.length"
        style="max-height: 45vh; overflow-y: auto; display: block"
      > -->
			<el-table :data="tableData" style="width: 100%" :height="is_ctdd_show ? '54vh' : '60vh'"
				v-loading="tableLoading" element-loading-background="rgba(0, 0, 0, 0.8)" highlight-current-row
				@current-change="currentChange">
				<!--  @cell-click="clickItemTr" -->
				<el-table-column prop="rank" label="排行" width="100" v-if="is_ctdd_show">
					<template #default="{ $index }">
						<div class="index-color">{{ $index + 1 }}</div>
					</template>
				</el-table-column>
				<!-- <el-table-column :prop="is_ctdd_show ? 'roadname' : 'areaName'" label="辖区名称">
					<template #default="scope">
						<el-popover effect="light" trigger="hover" placement="top" width="auto">
							<template #default>
								<div>{{ scope.row.nodeId }}
									{{ scope.row.roadId }}-{{ scope.row.roadname || scope.row.areaName }}</div>
							</template>
							<template #reference>
								<div class="flex_between">
									<span>{{ scope.row.roadname || scope.row.areaName }}</span>
									<div v-if="!is_ctdd_show">
										<el-button link type="primary" size="small"
											@click.stop="clickItemTrNow(scope.row)">实时</el-button>
										<el-button link type="primary" size="small"
											@click.stop="clickItemTrCompare(scope.row)">对比统计</el-button>
									</div>
								</div>
							</template>
						</el-popover>
					</template>
				</el-table-column> -->
				<el-table-column :prop="is_ctdd_show ? 'roadname' : 'areaName'" label="辖区名称">
					<template #default="scope">
						<span>{{ scope.row.roadname || scope.row.areaName }}</span>
					</template>
				</el-table-column>
				<el-table-column :prop="is_ctdd_show ? 'roadname' : 'areaName'" label="交通指数">
					<template #default="scope">
						<span>{{ scope.row.congestIndex}}</span>
					</template>
				</el-table-column>
				<el-table-column :prop="is_ctdd_show ? 'roadname' : 'areaName'" label="拥堵里程">
					<template #default="scope">
						<span>{{ scope.row.congestLength }}</span>
					</template>
				</el-table-column>
				<el-table-column :prop="is_ctdd_show ? 'roadname' : 'areaName'" label="平均速度">
					<template #default="scope">
						<div class="flex_column">
							<span>{{ scope.row.avgSpeed }}</span>
							<el-button link type="primary" size="small"
								@click.stop="clickItemTrCompare(scope.row)">对比统计</el-button>
						</div>
					</template>

				</el-table-column>
				<el-table-column label="拥堵指数" width="100" v-if="is_ctdd_show">
					<template #default="{ row }">
						<span class="congestion-num" :class="{
                red: row.congestIndex > 2,
                orange: row.congestIndex > 1.5 && row.congestIndex < 2,
              }">{{ Number(row.congestIndex).toFixed(2) }}
						</span>
					</template>
				</el-table-column>
			</el-table>
			<!-- </div>
      <div class="not-data" v-else>暂无数据</div> -->
		</div>
		<!-- 对比统计弹窗 -->
		<div class="statistics-db" :class="{ show: dbShow }">
			<div class="child-box2" style="padding: 20px 0 0">
				<div style="color: #fff">{{ compareTitle }}</div>
				<div class="flex_start">
					<div>
						<div class="cus-date flex_start cus-date1">
							<div>时间段一</div>
							<!-- 	<div class="date">
								<el-date-picker v-model="date1" style="width: 260px" type="daterange"
									range-separator="至" value-format="YYYY-MM-DD" format="YYYY-MM-DD"
									start-placeholder="选择开始日期" end-placeholder="选择结束日期" @change="dataChange1" />
							</div> -->
							<div class="date">
								<el-date-picker v-model="date1" type="date" range-separator="至"
									value-format="YYYY-MM-DD" format="YYYY-MM-DD" start-placeholder="选择开始日期"
									end-placeholder="选择结束日期" @change="clickItemTrCompare" />
							</div>
							<!-- 	</div>
						<div class="cus-date flex_start"> -->
							<div style="color:#4FD17D">时间段二</div>
							<!-- 	<div class="date">
								<el-date-picker v-model="date2" style="width: 260px" type="daterange"
									range-separator="至" value-format="YYYY-MM-DD" format="YYYY-MM-DD"
									start-placeholder="选择开始日期" end-placeholder="选择结束日期" @change="dataChange2" />
							</div> -->
							<div class="date">
								<el-date-picker v-model="date2" type="date" range-separator="至"
									value-format="YYYY-MM-DD" format="YYYY-MM-DD" start-placeholder="选择开始日期"
									end-placeholder="选择结束日期" @change="clickItemTrCompare" />
							</div>
						</div>
					</div>
					<!-- 	<el-button type="primary" :icon="'Search'" style="margin-left: 5px"
						@click="queryCompare">查询</el-button> -->
				</div>

				<div class="title">
					<p>运行情况监测对比统计 </p>
				</div>
				<div class="flex_start">
					<el-radio-group v-model="radio" @change="radioInput">
						<el-radio label="全部"> </el-radio>
						<el-radio label="时间段一"> </el-radio>
						<el-radio label="时间段二"> </el-radio>
					</el-radio-group>

				</div>
				<div class="sub-title">
					<span>拥堵指数</span>
				</div>
				<div id="chart1" class="left-charts" v-if="dbShow"></div>
				<div class="sub-title">
					<span>平均速度</span>
				</div>
				<div id="chart2" class="left-charts"></div>
				<div class="sub-title">
					<span>拥堵里程</span>
				</div>
				<div id="chart3" class="left-charts"></div>
			</div>
		</div>

		<!-- 统计弹窗 -->
		<!-- <div class="statistics-dio" :class="{ show: sdShow }">
      <div class="head">
        <div class="back" @click="sdShow = false">
          <div style="margin-top: 3px"
            ><el-icon>
              <ArrowLeft /> </el-icon
          ></div>
          <div>返回</div>
        </div>
        {{ chartTitle }}
      </div>
      <div class="tabs-group">
        <div
          class="tabs-item"
          v-for="(item, index) in tabsList"
          :key="index"
          :class="{ active: tabsCurrent == index }"
          @click="tabsClick(index)"
          >{{ item.label }}</div
        >
      </div>
      <div class="mychart" id="mychart1"></div>
    </div> -->
	</div>
</template>
<script>
	import {
		defineComponent,
		inject,
		reactive,
		toRefs,
		onMounted,
		nextTick,
		computed,
		onBeforeUnmount,
		watchEffect,
	} from 'vue';
	import {
		useMapStore
	} from '@/store/modules/map';
	import customDatePicker from '@/components/customDatePicker';
	import {
		Search,
		ArrowLeft
	} from '@element-plus/icons-vue';
	import {
		getCongestionCurve,
		getSelectByParamsList,
		getQueryRoadRank,
		getCoordinateBySplitName,
		compare2AreaCongest,
		compareAreaCongest,
	} from '@/api/tomae';
	import {
		searchList
	} from '../static/keyArea';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';
	import {
		cancelAllReq
	} from '@/utils/request';
	import {
		addmarker
	} from '@/views/analysis/static/setPoint.js';
	import dayjs from 'dayjs';
	export default defineComponent({
		components: {
			customDatePicker
		},
		props: {
			is_ctdd_show: false,
		},
		emits: ['tags-click', 'get-date'],
		setup(props, {
			emit
		}) {
			const mapStore = useMapStore();

			const state = reactive({

				areaTypeCode: null,
				areaTypeCodeList: [{
					value: null,
					label: "请选择"
				}, {
					value: 0,
					label: "行政区"
				}, {
					value: 1,
					label: "街道"
				}, {
					value: 2,
					label: "商圈"
				}, {
					value: 3,
					label: "医圈"
				}, {
					value: 4,
					label: "学校"
				}, {
					value: 5,
					label: "景区"
				}],
				map: computed(() => mapStore.ownMap),
				markerList: [],
				data: [],
				datePicker: null,
				chartTitle: '',
				compareTitle: '',
				radio1: '1',
				periodRange: '',
				today: '',
				sameDay: {
					time: '',
					keywork: '',
					period: '',
				},
				timer: null,
				tabsCurrent: 0,
				tabsList: searchList.tabsList,
				periodOptions: searchList.periodOptions,
				granularityList: searchList.granularityList,
				roadTagList: searchList.roadTagList,
				// sortOrder: searchList.sortOrder,
				tableData: [],
				sdShow: false,
				dbShow: false,
				myChart: null,
				tableLoading: false,
				radius: '',
				centerPoint: '',
				currentRow: {},
				queryForm: {
					areaName: '',
				},
				chartData: {},
				analysisDate: [],
				date1: '',
				date2: '',
				tagesForm: {
					type: 1,
					roadType: 4,
					startDate: '',
					endDate: '',
					roadName: '',
				},
				compareParams: {
					areaId: '', // 重点片区ID，列表中的nodeId字段
					startDate: '', // 比较日期1的开始时间， 必填
					endDate: '', // 比较日期2的结束时间，必填
					compareStartDate: '', // 比较日期2开始时间， 必填
					compareEndDate: '',
				},
				radioCurrent: 0,
				radio: '全部',
				chart3: null,
				chart2: null,
				chart1: null,
				xData: [],
				xData1: [],
				xData2: [],
				list: [],
				list1: [],
				list2: [],
				firstList: [],
				firstList1: [],
				firstList2: [],
				secondList: [],
				secondList1: [],
				secondList2: [],
			});
			const echarts = inject('echarts');
			// 获取当前时间
			const getToday = () => {
				var date = new Date();
				var year = date.getFullYear();
				var dateArr = [
					date.getMonth() + 1,
					date.getDate(),
					date.getHours(),
					date.getMinutes(),
					date.getSeconds(),
				];
				for (var i = 0; i < dateArr.length; i++) {
					if (dateArr[i] >= 1 && dateArr[i] <= 9) {
						dateArr[i] = '0' + dateArr[i];
					}
				}
				var strDate =
					year +
					'-' +
					dateArr[0] +
					'-' +
					dateArr[1] +
					' ' +
					dateArr[2] +
					':' +
					dateArr[3] +
					':' +
					dateArr[4];
				state.today = strDate;
				if (state.currentRow && JSON.stringify(state.currentRow) !== '{}') {
					getAreaChart;
				}
			};
			// 刷新
			const realRefresh = () => {
				getToday();
				clearTimeout(state.timer);
				state.timer = setTimeout(() => {
					realRefresh();
				}, 1000 * 60 * 5);
			};

			//实时 对比统计
			const changeRadio = (val) => {
				console.log('val', val);
				state.radio1 = val;
				if (val == 1) {} else {
					state.sdShow = false;
					state.dbShow = true;
				}
			};

			// 获取列表
			const getList = async () => {
				if (state.tableLoading) {
					cancelAllReq();

					// return;
				}
				state.currentRow = {};
				state.tableLoading = true;
				// 判断为交通运行界面
				if (props.is_ctdd_show) {
					state.tagesForm.roadName = state.queryForm.areaName;
					const data = await getQueryRoadRank(state.tagesForm);
					state.tableData = data;
				} else {
					const data = await getSelectByParamsList(state.queryForm);
					console.log('重点区域', data);
					state.tableData = data;
					makerList(data);
				}
				state.tableLoading = false;
			};

			const areaTypeCodeChange = () => {
				state.queryForm.areaTypeCode = state.areaTypeCode;

				getList();
			};
			const clearAllMarker = () => {
				state.markerList = [];
				state.map.clearOverlays();
			};
			const makerList = (list) => {
				clearAllMarker();
				if (!list?.length) return;
				const map = state.map;
				// map.removeEventListener('click')
				list.map((i) => {
					const type = areaNameIncludes(i.areaName);
					// console.log("type",type);
					// console.log("-0-0-",i);
					if (type) {
						state.data.push({
							...i,
							type
						});
						const centerPoint = i.coordinate.split(',');
						const point = new window.BMap.Point(centerPoint[0], centerPoint[1]); // 创建点坐标


						state.map.centerAndZoom(point, 13);
						const marker = addmarker(map, {
							lng: centerPoint[0],
							lat: centerPoint[1],
							title: i.areaName,
							congestIndex: i.congestIndex,
							areaId: i.areaId,
							type,
						});

						state.markerList.push(marker);
						map.addOverlay(marker);


						marker.addEventListener('click', (e) => {
							const markerData = marker.getPosition();
							// console.log(markerData);
							state.show = true;
							// nextTick(() => {
							//   console.log(e);
							//   console.log(markerData);
							//   state.popRef.open(e, markerData);
							// });
						});
					}
				});
			};
			const areaNameIncludes = (areaName) => {
				let type = '';
				if (areaName.includes('医院')) {
					type = 2;
				} else if (areaName.includes('学')) {
					type = 3;
				} else if (areaName.includes('场')) {
					type = 1;
				} else if (!areaName.includes('区')) {
					type = 1;
				}
				return type;
			};

			// 表格选择
			const currentChange = (currentRow) => {
				state.currentRow = currentRow;
				state.compareTitle = currentRow.areaName;
				if (!currentRow) {
					return;
				}
				console.log('currentRow', currentRow);
				// console.log("props.is_ctdd_show",props.is_ctdd_show);
				// 判断为交通运行界面
				if (props.is_ctdd_show) {
					emit('tags-click', currentRow);
					//左侧列表点击地图定位 2023-08-24
					clickItemTr(currentRow);
				} else {
					state.sdShow = true;
					// state.dbShow = false;
					drowEditor(currentRow);
					getAreaChart(currentRow);
				}
			};
			//单行点击
			const clickItemTr = async (row) => {
				// debugger
				const data = await getCoordinateBySplitName({
					roadName: row.roadname
				});
				if (data.lng && data.lat) {
					const conPoint = new window.BMap.Point(data.lng, data.lat);

					state.map.centerAndZoom(conPoint, 16);
				}

				// console.log("data",data);
			};
			const clickItemTrNow = (row) => {
				clickItemTr(row);
				currentChange(row);
			};
			const clickItemTrCompare = (row) => {
				// console.log('row---', row);
				state.compareTitle = row.areaName;
				state.sdShow = false;
				state.dbShow = true;
				let ddd = [
					dayjs().endOf('day').subtract(1, 'day').format('YYYY-MM-DD'),
					dayjs().endOf('day').format('YYYY-MM-DD'),
				];
				console.log(state.date1, state.date2)
				state.date1 = state.date1 || ddd[0]
				state.date2 = state.date2 || ddd[1]
				state.areaId = row.areaId || state.areaId

				state.compareParams = {
					dateTime: state.date1,
					compareDateTime: state.date2,
					areaId: state.areaId,
					// dateTime: '2025-01-12',
					// compareDateTime: '2025-01-13',
					// areaId: "8451",
				};
				state.chart1?.clear();
				state.chart2?.clear();
				state.chart3?.clear();
				queryCompare()
			};
			const initData = async () => {
				const initDataList = await compare2AreaCongest(state.compareParams);
				const {
					result1,
					result2
				} = initDataList;
				let setDataList = [];
				// 拥挤指数
				state.congestIndex = [
					[],
					[]
				]
				state.congestIndex[0] = result1.map((item) => {
					item = item.congestIndex
					return item
				})
				state.congestIndex[1] = result2.map((item) => {
					item = item.congestIndex
					return item
				})
				// 实时速度
				state.avgSpeed = [
					[],
					[]
				]
				state.avgSpeed[0] = result1.map((item) => {
					item = item.avgSpeed
					return item
				})
				state.avgSpeed[1] = result2.map((item) => {
					item = item.avgSpeed
					return item
				})
				// 拥挤里程
				state.congestLength = [
					[],
					[]
				]
				state.congestLength[0] = result1.map((item) => {
					item = item.congestLength
					return item
				})
				state.congestLength[1] = result2.map((item) => {
					item = item.congestLength
					return item
				})
				if (state.radioCurrent === 1) {
					state.congestIndex[1] = []
					state.avgSpeed[1] = []
					state.congestLength[1] = []
				}
				if (state.radioCurrent === 2) {
					state.congestIndex[0] = []
					state.avgSpeed[0] = []
					state.congestLength[0] = []
				}
				console.log(state)
				chart1();
				chart2();
				chart3();
			};

			const queryCompare = () => {
				//  console.log('compareParams', state.compareParams);
				//  if(!state.compareParams.startDate && !state.compareParams.compareStartDate){
				//    ElMessage({
				//       message: '请选择时间段',
				//       type: 'warning',
				//     });
				//     return;
				//  }
				//  if(!state.compareParams.compareStartDate){
				//    ElMessage({
				//       message: '请选择时间段二',
				//       type: 'warning',
				//     });
				//     return;
				//  }
				state.chart1?.clear();
				state.chart2?.clear();
				state.chart3?.clear();
				// state.xData1 = [];
				// state.firstList = [];
				// state.firstList1 = [];
				// state.firstList2 = [];
				// state.xData2 = [];
				// state.secondList = [];
				// state.secondList1 = [];
				// state.secondList2 = [];
				initData();
			};
			const radioInput = (val) => {
				if (val == '时间段一') {
					state.radioCurrent = 1;
				} else if (val == '时间段二') {
					state.radioCurrent = 2;
				} else {
					state.radioCurrent = 0;
				}
				initData();
			};
			const setLength = (data) => {
				var xlength;
				if (data.length > 7) {
					xlength = parseInt(data.length / 7);
				} else {
					xlength = 0;
				}
				return xlength;
			};
			const chart1 = () => {
				// 下面一半的不进行展示

				const chart1 = echarts.init(document.getElementById('chart1'));
				const fullXAxis = Array.from({
					length: 144
				}, (_, i) => {
					const totalMinutes = i * 10 + 5; // 每段增加10分钟，从5分钟开始
					const hour = Math.floor(totalMinutes / 60);
					const minute = totalMinutes % 60;
					return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
				});
				const option = {
					title: {
						textStyle: {
							fontSize: 12,
							fontWeight: 400,
						},
						left: 'center',
					},
					legend: {
						data: ['时间段一', '时间段二'],
						right: '40%',
						itemWidth: 6,
						itemGap: 20,
						textStyle: {
							color: '#fff',
						},
					},
					tooltip: {
						show: true,
						trigger: 'axis',
						axisPointer: {
							type: 'line',
						},
						formatter: (params) => {
							if (params.length > 0) {
								const index = params[0].dataIndex; // 获取数据索引
								const time = fullXAxis[index]; // 对应时间
								let content = `<div>${time}</div>`;
								params.forEach((item) => {
									content += `
				          <div>
				            <span style="color:${item.color}">●</span>
				            ${item.seriesName}: ${item.value}
				          </div>
				        `;
								});
								return content;
							}
							return '';
						},
					},
					grid: {
						top: '17%',
						bottom: '15%',
					},
					xAxis: {
						type: 'category',
						data: fullXAxis,
						axisTick: {
							show: true,
						},
						axisLabel: {
							formatter: (value, index) => (index % 4 === 0 ? value : ''), // 每小时显示一次
							textStyle: {
								color: '#fff',
							},
							fontSize: 12,
							margin: 5,
						},
					},
					yAxis: {
						type: 'value',
						interval: 0.5,
						min: 0.5,
						nameTextStyle: {
							color: '#fff',
							fontSize: 12,
						},
						axisTick: {
							show: false,
						},
						axisLabel: {
							textStyle: {
								color: '#fff',
							},
						},
						splitLine: {
							show: false,
						},
					},
					series: [{
							type: 'line',
							name: '时间段一',
							data: state.congestIndex[0] || [],
							lineStyle: {
								color: '#1891FD',
							},
							itemStyle: {
								color: '#1891FD',
							},
						},
						{
							type: 'line',
							name: '时间段二',
							data: state.congestIndex[1] || [],
							lineStyle: {
								color: '#4FD17D',
							},
							itemStyle: {
								color: '#4FD17D',
							},
						},
					],
				};

				setTimeout(() => {
					chart1.setOption(option);
				}, 500);
			};
			const chart2 = () => {
				// 下面一半的不进行展示
				const chart2 = echarts.init(document.getElementById('chart2'));
				const fullXAxis = Array.from({
					length: 144
				}, (_, i) => {
					const totalMinutes = i * 10 + 5; // 每段增加10分钟，从5分钟开始
					const hour = Math.floor(totalMinutes / 60);
					const minute = totalMinutes % 60;
					return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
				});
				let option = {
					title: {
						textStyle: {
							fontSize: 12,
							fontWeight: 400,
						},
						left: 'center',
					},
					legend: {
						data: ['时间段一', '时间段二'],
						right: '40%',
						itemWidth: 6,
						itemGap: 20,
						textStyle: {
							color: '#fff',
						},
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'line',
						},
						formatter: (params) => {
							if (params.length > 0) {
								const index = params[0].dataIndex; // 获取数据索引
								const time = fullXAxis[index]; // 对应时间
								let content = `<div>${time}</div>`;
								params.forEach((item) => {
									content += `
					      <div>
					        <span style="color:${item.color}">●</span>
					        ${item.seriesName}: ${item.value}
					      </div>
					    `;
								});
								return content;
							}
							return '';
						},
					},
					grid: {
						top: '17%',
						bottom: '15%',
					},
					xAxis: {
						type: 'category',
						data: fullXAxis,
						axisTick: {
							show: true,
						},
						axisLabel: {
							formatter: (value, index) => (index % 4 === 0 ? value : ''), // 每小时显示一次
							textStyle: {
								color: '#fff',
							},
							fontSize: 12,
							margin: 5,
						},
					},

					yAxis: {
						type: 'value',
						name: '单位(km/h)',
						nameTextStyle: {
							color: '#fff',
							fontSize: 12,
						},
						min: 10,
						axisTick: {
							show: false,
						},

						axisLabel: {
							textStyle: {
								color: '#fff',
							},
						},
						splitLine: {
							show: false,
						},
					},
					series: [{
							type: 'line', // 图表类型：折线图
							name: '时间段一', // 数据名称
							data: state.avgSpeed[0], // 第一组数据
							lineStyle: {
								color: '#1891FD', // 折线颜色
							},
							itemStyle: {
								color: '#1891FD', // 数据点颜色
							},
							width: 1 // 设置线条宽度为1px，使其更细
						},
						{
							type: 'line', // 图表类型：折线图
							name: '时间段二', // 数据名称
							data: state.avgSpeed[1], // 第二组数据
							lineStyle: {
								color: '#4FD17D', // 折线颜色
							},
							itemStyle: {
								color: '#4FD17D', // 数据点颜色
							},
						},
					],
				};
				chart2.setOption(option);
			};
			const chart3 = () => {
				// 下面一半的不进行展示
				const chart3 = echarts.init(document.getElementById('chart3'));
				const fullXAxis = Array.from({
					length: 144
				}, (_, i) => {
					const totalMinutes = i * 10 + 5; // 每段增加10分钟，从5分钟开始
					const hour = Math.floor(totalMinutes / 60);
					const minute = totalMinutes % 60;
					return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
				});
				let option = {
					title: {
						textStyle: {
							fontSize: 12,
							fontWeight: 400,
						},
						left: 'center',
					},
					legend: {
						data: ['时间段一', '时间段二'],
						right: '40%',
						itemWidth: 6,
						itemGap: 20,
						textStyle: {
							color: '#fff',
						},
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'line',
						},
						formatter: (params) => {
							if (params.length > 0) {
								const index = params[0].dataIndex; // 获取数据索引
								const time = fullXAxis[index]; // 对应时间
								let content = `<div>${time}</div>`;
								params.forEach((item) => {
									content += `
					      <div>
					        <span style="color:${item.color}">●</span>
					        ${item.seriesName}: ${item.value}
					      </div>
					    `;
								});
								return content;
							}
							return '';
						},
					},
					grid: {
						top: '17%',
						bottom: '15%',
					},
					xAxis: {
						type: 'category',
						data: fullXAxis,
						axisTick: {
							show: true,
						},
						axisLabel: {
							formatter: (value, index) => (index % 4 === 0 ? value : ''), // 每小时显示一次
							textStyle: {
								color: '#fff',
							},
							fontSize: 12,
							margin: 5,
						},
					},

					yAxis: {
						type: 'value',
						name: '单位(km)',
						nameTextStyle: {
							color: '#fff',
							fontSize: 12,
						},
						axisTick: {
							show: false,
						},

						axisLabel: {
							textStyle: {
								color: '#fff',
							},
						},
						splitLine: {
							show: false,
						},
					},
					series: [{
							type: 'line', // 图表类型：折线图
							name: '时间段一', // 数据名称
							data: state.congestLength[0], // 第一组数据
							lineStyle: {
								color: '#1891FD', // 折线颜色
							},
							itemStyle: {
								color: '#1891FD', // 数据点颜色
							},
							width: 1 // 设置线条宽度为1px，使其更细
						},
						{
							type: 'line', // 图表类型：折线图
							name: '时间段二', // 数据名称
							data: state.congestLength[1], // 第二组数据
							lineStyle: {
								color: '#4FD17D', // 折线颜色
							},
							itemStyle: {
								color: '#4FD17D', // 数据点颜色
							},
						},
					],
				};
				chart3.setOption(option);
			};
			// 统计图标签点击
			const tabsClick = (index) => {
				state.tabsCurrent = index;
				console.log(index)
				if (index == 0) {
					setOptions(state?.chartData?.congestIndex || 0, index);
				} else if (index == 1) {
					setOptions(state?.chartData?.congestLength || 0, index);
				} else {
					setOptions(state?.chartData?.avgSpeed || 0, index);
				}
			};
			const drowEditor = (item) => {
				state.map.clearOverlays();
				if (state.map.getZoom() < 16) {
					state.map.setZoom(16);
				}
				if (item.type === 'circle') {
					state.radius = item.radius;
					state.centerPoint = new window.BMap.Point(
						item.circle.split(',')[0],
						item.circle.split(',')[1],
					);
					// 绘制圆
					var circle = new window.BMap.Circle(state.centerPoint, state.radius, {
						strokeColor: '#5E87DB',
						fillColor: '#5E87DB', // 填充颜色。当参数为空时，圆形没有填充颜色
						strokeWeight: 3, // 边线宽度，以像素为单位
						strokeOpacity: 1, // 边线透明度，取值范围0-1
						fillOpacity: 0.2, // 填充透明度，取值范围0-1
					});
					state.map.panTo(state.centerPoint);
					state.map.addOverlay(circle);
					state.overlay = circle;
				} else {
					let arr = [];
					let lng = '';
					item.coordinate.split(',').forEach((item, index) => {
						if (index % 2 === 0) {
							lng = item;
						} else {
							arr.push(new window.BMap.Point(lng, item));
						}
					});
					var polygon = new window.BMap.Polygon(arr, {
						strokeColor: '#5E87DB',
						fillColor: '#5E87DB', // 填充颜色。当参数为空时，圆形没有填充颜色
						strokeWeight: 3, // 边线宽度，以像素为单位
						strokeOpacity: 1, // 边线透明度，取值范围0-1
						fillOpacity: 0.2, // 填充透明度，取值范围0-1
					});
					state.map.panTo(arr[0]);
					state.map.addOverlay(polygon);
					state.overlay = polygon;
				}
			};
			// 获取重点片区数据
			const getAreaChart = async (item) => {
				// console.log("item",item);
				state.chartTitle = state.currentRow.areaName;
				const data = await getCongestionCurve({
					// nodeId: state.currentRow.nodeId,
					areaName: state.currentRow.areaName,
					nodeId: 9093, //item.areaId 这个参数后端写死了是9093 前端传递无效
					// areaName: '临沂市人民医院',
				});
				if (data?.areaData?.length) {
					state.chartData = data.areaData[0];
				}
				tabsClick(0);
			};

			// 统计图渲染
			const setOptions = (num, index) => {
				let option = {
					// backgroundColor: '#transparent',
					title: {
						show: false,
					},
					grid: {
						top: 100,
					},
					tooltip: {
						show: false,
						formatter: '{a}：{b}{c}%'
					},
					series: [{
						name: '彩虹仪表盘',
						type: 'gauge',
						startAngle: 180,
						endAngle: 0,
						min: 0,
						max: 100,
						radius: '90%',
						center: ['50%', '50%'],
						axisLine: {
							show: true,
							lineStyle: {
								width: 20,
								shadowBlur: 0,
								color: [
									[0.05, '#cf3'],
									[0.1, '#9f3'],
									[0.15, '#6f3'],
									[0.2, '#3f3'],
									[0.25, '#3f6'],
									[0.3, '#3f9'],
									[0.35, '#3fc'],
									[0.4, '#3ff'],
									[0.45, '#3cf'],
									[0.5, '#39f'],
									[0.55, '#36f'],
									[0.6, '#33f'],
									[0.65, '#63f'],
									[0.7, '#93f'],
									[0.75, '#c3f'],
									[0.8, '#f3f'],
									[0.85, '#f3c'],
									[0.9, '#f39'],
									[0.95, '#f36'],
									[1, '#f33'],
								],
							},
						},
						axisTick: {
							show: true, //小刻度
						},
						axisLabel: {
							show: false,
							textStyle: {
								fontSize: 12,
							},
						},
						splitLine: {
							show: true,
						},
						pointer: {
							show: true,
							width: '2%',
							length: '90%',
							color: 'red',
						},
						title: {
							offsetCenter: [0, '-55%'],
							textStyle: {
								fontSize: 12,
								color: '#fff',
							},
						},
						detail: {
							formatter: `{value}${index == 1 ? 'km' : index == 2 ? 'km/h' : ''}`,
							offsetCenter: ['0', '-30%'],
							textStyle: {
								fontSize: 24,
								color: '#fff',
							},
						},
						data: [{
							value: parseFloat(num).toFixed(2) || 0,
							name: state.tabsList[state.tabsCurrent].label,
						}, ],
					}, ],
				};
				state.myChart.setOption(option);
			};
			// 粒度点击
			const granularityClick = (index) => {
				state.tagesForm.type = index;
				if (index == 0) {
					getToday();
					state.timer = setTimeout(() => {
						realRefresh();
					}, 1000 * 60 * 5);
				} else {
					clearTimeout(state.timer);
				}
				getList();
			};
			const tagClick = (index, key) => {
				state.tagesForm[key] = index;
				getList();
			};

			const dataChange1 = (val) => {
				// console.log('val', val);
				state.date1 = val;
				state.compareParams = {
					...state.compareParams,
					startDate: val[0],
					endDate: val[1],
				};
			};
			const dataChange2 = (val) => {
				state.date2 = val;
				state.compareParams = {
					...state.compareParams,
					compareStartDate: val[0],
					compareEndDate: val[1],
				};
			};

			// 自定义时间选择
			const changeAnalysisDate = (val) => {
				state.tagesForm.startDate = val[0];
				state.tagesForm.endDate = val[1];
				emit('query-date', state.tagesForm);
				getList();
			};
			// const changeTable = (val) => {
			//   if (state.currentRow && JSON.stringify(state.currentRow) !== '{}') {
			//     emit('table-select', state.tagesForm);
			//   }
			// };
			onMounted(() => {
				getToday();
				getList();
				state.timer = setTimeout(() => {
					realRefresh();
				}, 1000 * 60 * 5);

				// 初始化统计图
				// nextTick(() => {
				// 	state.myChart = echarts.init(document.getElementById('mychart1'));
				// });
			});
			// 页面离开
			onBeforeUnmount(() => {
				clearTimeout(state.timer);
			});

			return {
				...toRefs(state),
				realRefresh,
				currentChange,
				clickItemTr,
				clickItemTrNow,
				clickItemTrCompare,
				Search,
				ArrowLeft,
				tabsClick,
				getList,
				drowEditor,
				changeRadio,
				granularityClick,
				tagClick,
				// changeTable,
				changeAnalysisDate,
				dataChange1,
				dataChange2,
				queryCompare,
				initData,
				radioInput,
				areaTypeCodeChange
			};
		},
	});
</script>
<style scoped lang="less">
	#chart1 {
		position: relative;
		z-index: 10;
		pointer-events: auto;

		.echarts-tooltip {
			z-index: 9999;
		}

	}


	.flex_column {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.tag-group {
		display: flex;
		color: rgba(255, 255, 255, 0.7);
		align-items: center;
		margin: 0 0 1vw;

		.tag-label {
			padding-right: 1vw;
		}

		.tag-cell {
			display: flex;
		}

		.tag-item {
			padding: 4px 10px;
			cursor: pointer;
			margin-right: 0.5vw;

			&:last-child {
				margin-right: 0;
			}
		}

		.tag-item.active {
			color: white;
			background: #037bff;
			border-radius: 4px;
		}

		.today {
			display: flex;
			justify-content: space-between;
			flex-grow: 1;

			.date-box {
				color: white;
			}

			.refresh {
				cursor: pointer;
				color: #4979ff;
			}
		}

		.date {
			border: 1px solid rgba(3, 123, 255, 1);
			border-radius: 4px;
			flex: 1;
		}
	}

	.search {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.search-input {
			border: 1px solid #037bff;
			border-radius: 8px;
			flex-grow: 3;
		}

		.export {
			flex-grow: 2;
			color: rgba(3, 123, 255, 1);
			display: flex;
			text-align: right;
			align-items: center;
			justify-content: flex-end;

			span {
				cursor: pointer;
			}
		}
	}

	// .table {
	//   margin: 1.5625vw 0;
	//   width: 100%;
	:deep(.el-table) {
		margin-top: 1.5625vw;
		min-height: 80%;

		thead tr {
			background: linear-gradient(-90deg, #037bff 0%, #3996fc 100%) !important;
			box-shadow: 0px 4px 0px 0px rgba(77, 150, 236, 0.4);
			border-radius: 8px 0px 8px 0px;
		}

		.el-table__inner-wrapper::before {
			display: none;
		}

		.el-table__cell {
			padding: 15px 0;
		}

		.el-table__body tr.current-row {
			border: 1px solid #047cff !important;
			border-radius: 8px;
		}

		.el-table__body tr.current-row>td.el-table__cell {
			background: rgba(77, 150, 236, 0.4);
		}
	}

	:deep(.el-table__body) {
		.index-color {
			width: 20px;
			height: 20px;
			line-height: 20px;
			text-align: center;
			border-radius: 50%;
		}

		.congestion-num {
			color: rgba(117, 197, 31, 1);
		}

		.congestion-num.orange {
			color: rgba(248, 162, 46, 1);
		}

		.congestion-num.red {
			color: rgba(244, 59, 29, 1);
		}

		& tr:nth-child(1) {
			& td:first-child {
				.index-color {
					background: #fb6036;
					color: white;
				}
			}
		}

		& tr:nth-child(2) {
			& td:first-child {
				.index-color {
					background: rgba(151, 203, 243, 1);
					color: white;
				}
			}
		}

		& tr:nth-child(3) {
			& td:first-child {
				.index-color {
					background: rgba(177, 102, 53, 1);
					color: white;
				}
			}
		}
	}

	// }
	.statistics-dio {
		position: absolute;
		left: calc(100% + 10px);
		height: 80vh;
		top: 0;
		width: 27.0833vw;
		background: rgba(0, 0, 0, 0.8);
		transform: translateX(-100vw);
		transition: all 0.5s;
		z-index: 9;
		display: flex;
		flex-direction: column;

		.head {
			text-align: center;
			color: white;
			font-size: 1.0416vw;
			position: relative;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 1.0416vw;

			.back {
				left: 0.5vw;
				position: absolute;
				cursor: pointer;
				display: flex;
				align-items: center;
				font-size: 14px;
			}
		}

		.tabs-group {
			//   margin: 1.5625vw 0;
			display: flex;
			align-items: center;

			.tabs-item {
				flex-grow: 1;
				text-align: center;
				position: relative;
				color: rgba(255, 255, 255, 0.3);
				padding: 1.125vw;
				cursor: pointer;
			}

			.tabs-item.active {
				color: white;
			}

			.tabs-item.active::after {
				position: absolute;
				content: '';
				width: 30px;
				height: 4px;
				background: #037bff;
				border-radius: 2px;
				bottom: 0.5vw;
				left: 50%;
				margin-left: -15px;
			}

			.tabs-line {
				width: 1px;
				height: 18px;
				background: #ffffff;
				opacity: 0.3;
			}
		}

		.mychart {
			width: 100%;
			height: 0;
			flex-grow: 1;
			margin-top: 6vh;
		}
	}

	.statistics-dio.show {
		transform: translateX(0);
	}

	.statistics-db {
		position: fixed;
		right: 10px;
		height: 90vh;
		top: 100px;
		//width: 27.0833vw;
		width: 50vw;
		background: rgba(0, 0, 0, 0.8);
		transform: translateX(-100vw);
		transition: all 0.5s;
		z-index: 9;
		display: flex;
		flex-direction: column;

		.child-box2 {
			width: 100%;
			height: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;
			position: relative;
			padding-top: 40px;

			.cus-date {
				// color: #fff;
				color: greenyellow;
			}

			.cus-date1 {
				color: rgba(3, 123, 255, 1);
			}

			.title {
				width: 100%;
				height: 42px;
				margin-left: 10px;
				display: flex;
				align-items: center;
				background: url(@/assets/images/report/leftTitle.png) no-repeat;

				p {
					font-size: 18px;
					color: white;
					margin-left: 10px;
					font-weight: 400;
				}
			}

			.sub-title {
				width: 100%;
				padding: 0 20px;

				span {
					color: #fff;
				}
			}

			.left-charts {
				height: 28%;
				width: 100%;
				margin: 10px 0;
			}
		}
	}

	.statistics-db.show {
		transform: translateX(0);
	}
</style>
<style lang="less" scoped>
	.el-popper.is-light {
		background-color: rgba(5, 12, 23) !important;
		border: 1px solid #3d618a54 !important;
	}

	.not-data {
		padding-top: 1vw;
		color: white;
	}
</style>